﻿using System;
using System.IO;

namespace YG.CommonFuncs
{
    /// <summary>
    /// 文件保存action
    /// </summary>
    public static class SaveFileToLocalFunc
    {
        /// <summary>
        /// 把文件保存到本地
        /// </summary>
        /// <param name="_byte">文本内容</param>
        /// <param name="fileName">文件名字，带后缀</param>
        /// <param name="version1">接口版本</param>
        /// <param name="interFace">API名字</param>
        /// <param name="programPath">程序原始路经</param>
        /// <returns>返回文件存储的绝对路径</returns>
        public static string SaveFileToLocal(byte[] _byte, string fileName = "", string analysisTpye = "", string version1 = "", string interFace = "", string programPath = "")
        {
            try
            {
                //拼接存储的文件夹名
                string log = "logfile";
                string dateTime = DateTime.Now.ToString("yyyy_MM_dd_HH");//样例 2019_09_05_08
                string filePath = Path.Combine(programPath, log);
                filePath = Path.Combine(filePath, dateTime);
                filePath = Path.Combine(filePath, analysisTpye);
                filePath = Path.Combine(filePath, version1 + "_" + interFace);
                //拼接文件夹名结束

                string folderPath = filePath;

                //一定要先创建外层文件夹，否则在后面调用byte2file方法会报错
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                //拼接文件名字，得到文件的绝对路径
                filePath = Path.Combine(filePath, fileName);
                //_logger.LogInformation("保存的文件名字:" + filePath);

                if (FileAction.FindFile(filePath))
                {
                    //_logger.LogInformation("已经check到文件已存在:" + filePath);
                    FileAction.DeleteFile(filePath);
                }
                else
                {
                    //_logger.LogInformation("已经check到文件不存在:" + filePath);
                }

                //写入文件
                FileBinaryConvert.Bytes2File(_byte, filePath);

                //_logger.LogInformation("文件写入成功:" + filePath);

                return filePath;
            }
            catch (Exception)
            {
                return "fail";
            }
        }
    }
}